package com.sky.service.common.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.common.DishFlavorMapper;
import com.sky.mapper.common.DishMapper;
import com.sky.mapper.common.SetmealMapper;
import com.sky.pojo.Dish;
import com.sky.pojo.DishFlavor;
import com.sky.result.PageResult;
import com.sky.service.common.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 新增菜品
     *
     * @param dto
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(DishDTO dto) {
        Dish d=new Dish();
        BeanUtils.copyProperties(dto,d);

        dishMapper.add(d);
        if (!CollectionUtils.isEmpty(dto.getFlavors())) {
            dishFlavorMapper.add(dto.getFlavors());
        }
        clearCache("dish:categoryId:"+dto.getCategoryId());
    }

    /**
     * 菜品分页条件查询
     *
     * @param dto
     * @return
     */
    @Override
    public PageResult page(DishPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        Page<DishVO> p= dishMapper.page(dto);


        return new PageResult(p.getTotal(),p.getResult());
    }

    /**
     * 批量删除菜品
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<Integer> ids) {
       Integer counts= dishMapper.onSaleCount(ids, StatusConstant.ENABLE);
       if (counts>0){
           throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
       }
       if (setmealMapper.associateCount(ids)>0){
           throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
       }
       dishFlavorMapper.deleteByDishId(ids);
       dishMapper.delete(ids);
       clearCache("dish:categoryId:*");
    }

    /**
     * 查询回显
     *
     * @param id
     * @return
     */
    @Override
    public DishVO getInfo(Integer id) {
       DishVO d= dishMapper.getInfo(id);
       d.setFlavors(dishFlavorMapper.getInfo(id));
        return d;
    }

    /**
     * 修改菜品
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(DishDTO dto) {
        Dish dish=new Dish();
        BeanUtils.copyProperties(dto,dish);
        dishMapper.update(dish);
        if (!CollectionUtils.isEmpty(dto.getFlavors())) {
            dishFlavorMapper.deleteByDishId(List.of(dto.getId().intValue()));
            List<DishFlavor> flavors = dto.getFlavors();
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dto.getId());
            }

            dishFlavorMapper.add(flavors);
        }
        clearCache("dish:categoryId:*");
    }

    /**
     * 分类id查菜品
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> getBycId(Integer categoryId) {

        return dishMapper.getBycId(categoryId);
    }
    /**
     * 条件查询菜品和口味
     *
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.getBycId(dish.getCategoryId().intValue());


        List<DishVO> dishVOList=(List<DishVO>) redisTemplate.opsForValue().get("dish:categoryId:"+dish.getCategoryId());

        if (!CollectionUtils.isEmpty(dishVOList)) {
           return dishVOList;
        }
        dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }
        redisTemplate.opsForValue().set("dish:categoryId:"+dish.getCategoryId(),dishVOList);
        return dishVOList;
    }
    /**
     * 清理缓存
     */
    public void clearCache(String keyPattern){
        Set keys = redisTemplate.keys(keyPattern);
        keys.forEach(k->redisTemplate.delete(k));
    }
}
